package com.deng.controller;

import com.deng.Service.ColumnService;
import com.deng.Service.PaperService;
import com.deng.Service.TagService;
import com.deng.Service.UserService;
import com.deng.config.common.FreezeException;
import com.deng.config.common.InsertPojo;
import com.deng.config.common.ModifyPass;
import com.deng.config.common.Paging;
import com.deng.model.To.UserAndRoles;
import com.deng.model.User;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @Author 邓小熙
 * @Date 2022/5/2 14:15
 * @Version 1.0
 */
@Controller
public class UserController {

    private static final int SUCCESS_FOR_NOW = 1 ;
    Logger logger = Logger.getLogger(this.getClass().getName());
    @Autowired
    UserService userService;
    @Autowired
    ModifyPass modifyPass;
    @Autowired
    PaperService paperService;
    @Autowired
    TagService tagService;
    @Autowired
    ColumnService columnService;
    /**
     *返回login登录界面
     */
    @RequestMapping(value = "/user/login")
    public String login(){
        return "login";
    }
    /**
     * 用户登录
     */
//    @Log(operationName = "用户登录")
    @RequestMapping(value = "/user/gotoIndex")
    public String gotoIndex(@RequestParam("username") String username
                , @RequestParam("password") String password
                , @RequestParam(value = "rememberMe",required = false) String rememberMe
                , HttpServletRequest request
                ,@RequestParam(value = "url",required = false) String url){
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        HttpSession session = request.getSession();
        String reDirectUrl;
        if (url == null || "".equals(url)){
            reDirectUrl = url;
        }else {
            reDirectUrl = "/main/index";
        }
        logger.info("url" + reDirectUrl + (url == null));
//          设置rememberMe
        if ("on".equals(rememberMe)) {
            usernamePasswordToken.setRememberMe(true);
            logger.info("开启 rememberMe 功能");
        }else {
            usernamePasswordToken.setRememberMe(false);
            logger.info("未开启 rememberMe 功能");
        }
        try {
            if (userService.findUserByName(username).getStatus()==0){
                logger.info("账户已经被冻结");
                throw new FreezeException("账户已经被冻结");
            }
            subject.login(usernamePasswordToken);
            session.setAttribute("user",username);
            return "redirect:" + reDirectUrl;
        }catch (Exception e){
            e.printStackTrace();
            return "login";
        }

    }
    /**
     * 登出
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/logout")
    public String logout(HttpServletRequest request){
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/user/login";

    }
    @RequestMapping(value = {"/userMes/{name}","/main/userMes/{name}"})
    public @ResponseBody User userMes(
            @PathVariable("name") String name){
        return userService.findUsersByName(name);
    }

    /**
     * 个人简介
     * @param userName
     * @return
     */
    @RequestMapping(value = "/main/user/personalMes")
    public @ResponseBody
    User personalMes(@RequestParam("userName") String userName){
        return userService.findUsersByName(userName);
    }

    /**
     * 后台用户完善信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/detailPage")
    public @ResponseBody
    ModelAndView getDetail(HttpServletRequest request){
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("user");
        ModelAndView modelAndView = new ModelAndView("InnerLayui/userDetail");
//        modelAndView.setViewName("InnerLayui/userDetail");
        modelAndView.addObject("user",userService.getUserParam(name));
        return modelAndView;
    }

    /**
     * 改变用户头像
     * @return
     */
    @RequestMapping(value = "/user/headPic")
    public String headPic(){

        return "InnerLayui/caozuo/pic";
    }
//    @RequestMapping(value = "/user/edictDetail")
//    public String edictDetail(@RequestParam("username")String username){
//        AllParamOfUser allParamOfUser = userService.getUserParam(username);
//        AllParamOfUser allParamOfUser1 = userService.edictDetail(allParamOfUser);
//        return "friendPage";
//    }
    /**
     * 更新用户信息
     * @param imgMes
     * @param userName
     * @param realName
     * @param position
     * @param data
     * @param email
     * @param address
     * @param sketch
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/user/updateDetail")
    public @ResponseBody int updateUserDetail(@RequestParam("imgMes") String imgMes,
                                              @RequestParam("userName") String userName,
                                              @RequestParam("realName") String realName,
                                              @RequestParam("position") String position,
                                              @RequestParam("date") String data,
                                              @RequestParam("email") String email,
                                              @RequestParam("address") String address,
                                              @RequestParam("sketch") String sketch) throws ParseException {
        return userService.updateUserMes(imgMes, userName, realName, position, data, email, address, sketch);
    }

    /**
     * 后台人员管理
     * @param url
     * @return
     */
    @RequiresPermissions("can_manage")
    @RequestMapping(value = "/user/returnUserManage")
    public ModelAndView returnUserManage(@RequestParam(value = "url",required = false) String url){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("InnerLayui/admin/userManage");
        modelAndView.addObject("url",url);
        return modelAndView;
    }

    /**
     * 人员状态管理
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/admin/updateUserStatus")
    public ModelAndView updateUserStatusPage(@RequestParam(value = "id",required = true) int id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("currentUserId",id);
        modelAndView.setViewName("InnerLayui/admin/updateUserStatus");
        return modelAndView;
    }

    /**
     * 显示所有人员（分页）
     * @param pageNum
     * @return
     */
    @RequestMapping(value = "/user/userManage/{pageNum}")
    public @ResponseBody
    Map<String,Object> userManage(@PathVariable("pageNum") int pageNum){
        int limit = Paging.LIMIT.getValue();
        Map<String,Object> map = Maps.newHashMap();
//        Map<String,Object> map = new HashMap<>();
        List<UserAndRoles> list = userService.userAndRole(pageNum);
//        List<UserAndRoles> list = userService.userAndRole((pageNum-1) * limit,limit);
        int count = userService.findAllUsers().size();
        map.put("data",list);
        map.put("code",0);
        map.put("msg","");
        map.put("pageNum", pageNum);
        map.put("limit", limit);
        map.put("count",count);
//        Gson gson =new Gson();
//        String userString=gson.toJson(list);//先将得到的集合Users转化成json字符串
//        String userInfo="{\"code\":\"0\",\"msg\":\"ok\",\"count\":1,\"data\":"+userString+"}";
//        //用了一个字符串拼接的方式，使返回的数据变成Layui的支持的数据类型
        return map;
    }
    /**
     * 人员状态修改
     * @param review
     * @param status
     * @param userid
     * @return
     */
    @RequestMapping(value = "/user/updateUserStatus/{id}")
    public @ResponseBody int updateUserStatus(@RequestParam String review,@RequestParam String status,@PathVariable(value = "id") String userid){
        int user = Integer.parseInt(userid);
        logger.info("userid =" + userid+"review="+review+"status="+status);
        return userService.updateUserStatus(review, status, user);
    }

    /**
     * 后台文章审查中的文章发表博主部分信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/admin/CheckUserMesPage")
    public @ResponseBody ModelAndView returnCheckUserMesPage(@RequestParam(value = "id",required = false) int id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user",userService.checkUserMes(id));
        modelAndView.setViewName("InnerLayui/admin/caozuo/checkUserMes");
        return modelAndView;
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param newPassword1
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/updateUserPass")
    public @ResponseBody int updateUserPass(@RequestParam("oldPassword") String oldPassword,
                                            @RequestParam("newPassword")String newPassword,
                                            @RequestParam("newPassword1")String newPassword1,HttpServletRequest request){
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("user");

        if(modifyPass.checkOldPassWordIsRight(userName,oldPassword) != SUCCESS_FOR_NOW){
            return modifyPass.checkOldPassWordIsRight(userName,oldPassword);
        }
        else if(modifyPass.checkNewPassIsNotNull(newPassword,newPassword1) != SUCCESS_FOR_NOW ){
            return modifyPass.checkNewPassIsNotNull(newPassword,newPassword1);

        }else if(modifyPass.checkIsEquals(newPassword, newPassword1) != SUCCESS_FOR_NOW){
            return modifyPass.checkIsEquals(newPassword, newPassword1);
        }
        else {
            return userService.updateUserPass(userName,newPassword,oldPassword);
        }
    }


    /**
     * 新建文章
     * @param insertPojo 插入的数据类型
     * @return 返回值 根据返回值判断是否返回成功
     */
    @RequestMapping(value = "/paper/insertAll/{user}")
    public @ResponseBody int insertAll(
            InsertPojo insertPojo
            ,HttpServletRequest request
//            ,@RequestParam(value = "paper_image",required = false) String paper_image
            , @PathVariable("user") String user){
        String title = insertPojo.getTitle();
        String content = insertPojo.getMain1();
        String newTag = insertPojo.getNewTag();
        String segment = insertPojo.getSegment();
//        String paper_image = insertPojo.getPaper_image();
        List<String> tags = Lists.newLinkedList();
        List<String> tag = insertPojo.getTag();
//       String paper_image = (String) request.getAttribute("msg");
        String paper_image = (String) request.getSession().getAttribute("msg");
        System.out.println(paper_image);
        addTags(tags,tag,newTag);

        String theme = insertPojo.getTheme();
        // 插入里一条paper的记录 自动生成一个id值
        int result = paperService.insertPaper(title,content,segment,user,paper_image);
        // 根据信息查询paper的id
        int paperId = paperService.findPaperId(title,segment,user);
        // 插入tag和主题
        if(tags.size()!=0){
            tagService.insertTagByUserId(tags,paperId);
        }
        if(theme != null && !"".equals(theme)){
            int columnId = columnService.findColumnId(theme);
            int result1 = columnService.insertColumnPaper(columnId,paperId);
        }
        return result ;
    }

        /**
         * 根据条件添加tags
         * @param tags
         * @param tag
         * @param newTag
         */
        private void addTags(List<String> tags,List<String> tag ,String newTag){
            try{
                //判断是否是空
                Optional<String> optional = Optional.of(newTag);
                tags.add(newTag);
            }catch (NullPointerException n){
                logger.warning("the tag is null");
            }finally {
                tags.addAll(tag);
                logger.info("add tag operation is over");
            }
        }
}
